from datetime import datetime, timedelta
from django import forms
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.defaultfilters import slugify
from django.views.generic import date_based, list_detail 
from django.utils.translation import gettext as _
from models import Event

month_names = {'jan':0, 'feb':1, 'mar':2,
               'apr':3, 'may':4, 'jun':5,
               'jul':6, 'aug':7, 'sep':8,
               'oct':9, 'nov':10, 'dec':11}

def closest_events(request):
    """Displays upcoming events (i.e. events with dates from today
    to today + 30 days"""
    today = datetime.today()
    qs = Event.objects.filter(start_datetime__range = (today, today+timedelta(30))).order_by('start_datetime')
    return list_detail.object_list(request, queryset = qs,)

@login_required
def add_edit_event(request, id=None):
    if id is None:
        EventForm = forms.models.form_for_model(Event)
    else:
        event = Event.objects.get(id=id)
        EventForm = forms.models.form_for_instance(event)

    EventForm.base_fields['user'].widget = forms.widgets.HiddenInput()
    EventForm.base_fields['user'].required = False
    EventForm.base_fields['site'].widget = forms.widgets.HiddenInput()
    EventForm.base_fields['site'].required = False
    EventForm.base_fields['pub_date'].widget = forms.widgets.HiddenInput()
    EventForm.base_fields['pub_date'].required = False
    EventForm.base_fields['slug'].widget = forms.widgets.HiddenInput()
    EventForm.base_fields['slug'].required = False
    EventForm.base_fields['description'].widget = forms.widgets.HiddenInput()
    EventForm.base_fields['description'].required = False
    
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.user = request.user
            event.pub_date = datetime.now()
            event.slug = slugify(event.name)
            event.save()
            return HttpResponseRedirect(event.get_absolute_url())
    else:
        form = EventForm()

    return render_to_response('events/event_add.html', {'form':form})
